package com.cloud.basic.webservice.soapClient.resolver;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.cloud.basic.webservice.soapClient.SoapAcess.CommonAccess;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


public class SoapResolver{
	static final String RESULT="Result";
	static final String STRING="string";

	/**
	 * 获取结果集
	 * @throws DocumentException
	 */
	public static String getSoapResult(String xml, String soapAction) {
		String action = soapAction + RESULT;
		int[] index = findTag(xml, action);
		if (index != null && index.length > 1) {
			return xml.substring(index[0], index[1]);
		}
		return null;
	}
	/**
	 * 结果集是否为空（不是标准xml格式）
	 * @return
	 */
	public static boolean isStandardXml(String xml){
		try {
			Document doc = getParseDoc(xml);

			Element root=doc.getRootElement();
			String r=root.getName();
			System.err.println(r);
			if(r!=null){
				return true;
			}
		} catch (DocumentException e) {
			return false;
		}
		return false;
	}

	/**
	 * 替换xml中对应标签的数据
	 *
	 * @return
	 */
	private String replase(String xml, Map<String, String> map) {
		for (Entry<String, String> en : map.entrySet()) {
			String key = en.getKey();
			String value = en.getValue();
			int[] index = null;
			if ((index = findTag(xml, key)) != null && index.length > 1) {
				String temp1 = xml.substring(0, index[0]);
				String temp2 = xml.substring(index[1]);
				xml = temp1 + CommonAccess.STAG + key + CommonAccess.ETAG + value + temp2;
			}
		}
		return xml;
	}

	/**
	 * 查找一个完整标签（比如：<name>name</name>）
	 *
	 * @param xml
	 * @param tagName
	 * @return int[0]:标签开始位置，int[1]:标签正常结束位置
	 */
	public static int[] findTag(String xml, String tagName) {
		int len=tagName.length();
		int[] arr=null;
		if(xml!=null&&tagName!=null){
			arr=new int[2];
		}
		int start=-1;
		int end=-1;
		if((start=xml.indexOf(tagName))>=0){
			arr[0]=start-1;
			if((end=xml.indexOf(tagName,start+len))>=0){
				arr[1]=end+len+1;
			}
		}
		return arr;
	}

	/**
	 * 查找<>
	 * @param xml
	 * @param index
	 * @return
	 */
	public static int[] findStartTag(String xml,int index){
		int arr[]=null;
		if(xml!=null){
			arr=new int[2];
		}
		int start=-1;
		int end=-1;
		if((start=index(xml,"<",index))>=0){
			arr[0]=start;
			if((end=index(xml,">",index))>=0){
				arr[1]=end;
			}
		}
		return arr;
	}

	private static int index(String str, String i) {
		return str.indexOf(i);
	}

	private static int index(String str, String i,int index) {
		return str.indexOf(i,index);
	}

	// 创建文档
	private static Document getDoc() {
		return DocumentHelper.createDocument();
	}

	// 创建解析文档
	private static Document getParseDoc(String str) throws DocumentException {
		return DocumentHelper.parseText(str);
	}

	/**
	 * Map转xml
	 *
	 * @param map
	 * @return
	 */
	public static String mapToXml(String rootElement, Map<String, String> map) {
		Document doc = getDoc();
		Element root = doc.addElement(rootElement);
		for (Entry<String, String> entry : map.entrySet()) {
			Element e = root.addElement(entry.getKey());
			e.setText(entry.getValue());
		}
		return root.asXML();
	}

	/**
	 * listmap转xml
	 *
	 * @param rootElement
	 * @param listmap
	 * @return
	 */
	public static String listMapToXml(String rootElement, String listName, List<Map<String, String>> listMap) {
		Document doc = getDoc();
		Element root = doc.addElement(rootElement);
		for (Map<String, String> map : listMap) {
			Element listele = root.addElement(listName);
			for (Entry<String, String> entry : map.entrySet()) {
				Element e = listele.addElement(entry.getKey());
				e.setText(entry.getValue());
			}
		}
		return root.asXML();
	}

	/**
	 * List转xml
	 *
	 * @param rootElement
	 * @param list
	 * @return
	 */
	public static String listToXml(String rootElement, List<String> list) {
		Document doc = getDoc();
		Element root = doc.addElement(rootElement);
		for (String s : list) {
			Element e = root.addElement(STRING);
			e.setText(s);
		}
		return root.asXML();
	}

	/**
	 * string转xml
	 *
	 * @param rootElement
	 * @param str
	 * @return
	 */
	public static String stringToXml(String rootElement, String str) {
		Document doc = getDoc();
		Element root = doc.addElement(rootElement);
		root.setText(str);
		return root.asXML();
	}

	/**
	 * map无根转xml(string转xml的语法糖)
	 * @param map - 字符串键值对
	 * @return
	 */
	public static String mapToXml(Map<String,String> map){
		String xml=null;
		if(map!=null){
			for(Entry<String,String> en:map.entrySet()){
				if(xml==null){
					xml= stringToXml(en.getKey(),en.getValue());
				}else{
					xml+=stringToXml(en.getKey(),en.getValue());
				}
			}
			return xml;
		}
		return null;
	}

	/**
	 * list无根转xml(string转xml的语法糖)
	 * @param list -字符串列表
	 * @return
	 */
	public static String listToXml(List<String> list){
		String xml=null;
		if(list!=null){
			for(String l:list){
				if(xml==null){
					xml= stringToXml(STRING,l);
				}else{
					xml+=stringToXml(STRING,l);
				}
			}
			return xml;
		}
		return null;
	}

	/**
	 * list无根转xml(string转xml的语法糖)
	 * @param Array -字符串数组
	 * @return
	 */
	public static String listToXml(String... arr){
		String xml=null;
		if(arr!=null){
			for(String l:arr){
				if(xml==null){
					xml= stringToXml(STRING,l);
				}else{
					xml+=stringToXml(STRING,l);
				}
			}
			return xml;
		}
		return null;
	}

	/**
	 * string转xml(并增加xmlns)
	 * @param rootElement
	 * @param xmlns
	 * @param str
	 * @return
	 */
	public static String stringToXml(String rootElement,String xmlns, String str){
		Document doc = getDoc();
		Element root = doc.addElement(rootElement,xmlns);
		root.setText(str);
		return root.asXML();
	}

	/**
	 * 解析List<Map<String,String>>
	 *
	 * @param xml
	 * @return
	 */
	public static List<Map<String, String>> xmlToListMap(String xml) {
		List<Map<String, String>> list = null;
		if (xml != null) {
			list = new ArrayList<Map<String, String>>();
		}
		try {
			Document doc = getParseDoc(xml);
			Element root = doc.getRootElement();
			String name = root.getName();
			List<Element> eles = root.elements();
			for (Element ele : eles) {
				Iterator<Element> iter = ele.elementIterator();
				Map<String, String> map = new HashMap<String, String>();
				while (iter.hasNext()) {
					Element e = iter.next();
					map.put(e.getName().trim(), e.getTextTrim());
				}
				list.add(map);
			}
			return list;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 解析List数据
	 *
	 * @param xml
	 * @return
	 */
	public static List<String> xmlToList(String xml) {
		List<String> list = null;
		if (xml != null) {
			list = new ArrayList<String>();
		}
		try {
			Document doc = getParseDoc(xml);
			Element root = doc.getRootElement();
			String name = root.getName();
			List<Element> eles = root.elements();
			for (Element e : eles) {
				list.add(e.getTextTrim());
			}
			return list;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 解析map数据
	 *
	 * @param xml
	 * @return
	 */
	public static Map<String, String> xmlToMap(String xml) {
		Map<String, String> map = null;
		if (xml != null) {
			map = new HashMap<String, String>();
		}
		try {
			Document doc = getParseDoc(xml);
			Element root = doc.getRootElement();
			String name = root.getName();
			List<Element> eles = root.elements();
			for (Element e : eles) {
				map.put(e.getName(), e.getTextTrim());
			}
			return map;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 转换为string
	 *
	 * @param xml
	 * @return
	 */
	public static String xmlToString(String xml) {
		try {
			Document doc = getParseDoc(xml);
			Element root = doc.getRootElement();
			return root.getTextTrim();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 测试
	public static void main(String[] args) throws DocumentException {
		// 测试xml转换
//		List<Map<String, String>> maplist = xmlToListMap(
//				"<result><VehicleInfo> <ID>int</ID> <Code>string</Code> <PlateNo>string</PlateNo> <DeviceID>string</DeviceID> <LineID>int</LineID> <LineName>string</LineName> </VehicleInfo> <VehicleInfo> <ID>int</ID> <Code>string</Code> <PlateNo>string</PlateNo> <DeviceID>string</DeviceID> <LineID>int</LineID> <LineName>string</LineName> </VehicleInfo></result>");
//		for (Map<String, String> map : maplist) {
//			for (String key : map.keySet()) {
//				System.err.println("key=" + key + ",value=" + map.get(key));
//			}
//		}
//		List<String> list = xmlToList("<result><string>1</string><string>2</string><string>3</string></result>");
//		System.err.println(list);
//		Map<String, String> map = xmlToMap("<result><a>1</a><b>2</b><c>3</c></result>");
//		System.err.println(map);
//		System.err.println(xmlToString("<result>123</result>"));
//
//		// 测试转换为xml
//		System.err.println("转换结果：" + mapToXml("root", map));
//		System.err.println(listToXml("root", list));
//		System.err.println(stringToXml("root", "123"));
//		System.err.println(listMapToXml("root", "vehicleinfo", maplist));
//		String xml="<result><a>1</a><b>2</b><c>3</c></result>";
//		int[] i=findTag(xml,"b");
//		System.err.println(i[0]+","+i[1]);
//		System.err.println(xml.substring(i[0], i[1]));
//		System.err.println(isStandardXml("<result><string>1</string><string>2</string><string>3</string></result>"));
		System.err.println(getSoapResult("<xml><abcResult><VehicleInfo> <ID>int</ID> <Code>string</Code> <PlateNo>string</PlateNo> <DeviceID>string</DeviceID> <LineID>int</LineID> <LineName>string</LineName> </VehicleInfo> <VehicleInfo> <ID>int</ID> <Code>string</Code> <PlateNo>string</PlateNo> <DeviceID>string</DeviceID> <LineID>int</LineID> <LineName>string</LineName> </VehicleInfo></abcResult></xml>","/abcResult/*"));
	}
}
